﻿namespace iFinance.Infrastructure.Services
{
    using System;
    using System.Collections.Generic;
    using System.Windows.Controls;
    using Microsoft.Practices.Prism.ViewModel;

    /// <summary>
    /// ChildWindow服务
    /// </summary>
    public class ChildWindowService : IChildWindowService
    {
        private Dictionary<Type, Type> typeMappingDict = new Dictionary<Type, Type>();

        /// <summary>
        /// 注册ChildWindow
        /// </summary>
        /// <typeparam name="TViewModel">ChildWindow对应的ViewModel的类型.</typeparam>
        /// <typeparam name="TChildWindow">ChildWindow的类型</typeparam>
        public void Register<TViewModel, TChildWindow>()
            where TViewModel : NotificationObject
            where TChildWindow : ChildWindow
        {
            typeMappingDict[typeof(TViewModel)] = typeof(TChildWindow);
        }

        /// <summary>
        /// 创建ChildWindow
        /// </summary>
        /// <typeparam name="TViewModel">ChildWindow对应的ViewModel的类型.</typeparam>
        /// <returns></returns>
        public ChildWindow Resolve<TViewModel>() 
            where TViewModel : NotificationObject
        {
            if (typeMappingDict.ContainsKey(typeof(TViewModel)))
            {
                ChildWindow childWindow = Activator.CreateInstance(typeMappingDict[typeof(TViewModel)]) as ChildWindow;
                return childWindow;
            }
            return null;
        }

        /// <summary>
        /// 创建并显示ChildWindow
        /// </summary>
        /// <typeparam name="TViewModel">ChildWindow对应的ViewModel的类型.</typeparam>
        /// <param name="viewModel">所需要的ViewModel</param>
        /// <returns></returns>
        public bool ResolveAndShow<TViewModel>(TViewModel viewModel) 
            where TViewModel : NotificationObject
        {
            var childWindow = Resolve<TViewModel>();
            if (childWindow != null)
            {
                childWindow.DataContext = viewModel;
                childWindow.Show();
                return true;
            }
            return false;
        }
    }
}
